import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image, 
  Dimensions,ScrollView,WebView,Button,KeyboardAvoidingView,
  TouchableOpacity,Modal,TextInput,StatusBar,ReactNative,findNodeHandle
} from 'react-native';
import Toast, {DURATION} from 'react-native-easy-toast';
import { TipModal } from '../../component/Tips';
import Orientation from 'react-native-orientation';
import ImagePicker from 'react-native-image-crop-picker';
import BackButton from '../../component/BackButton';
import MyButton from '../../component/MyButton';
import {jumpPage} from '../../common/common';
import {BASEURL} from '../../api/api'
let {height, width} = Dimensions.get('window');
//width = 768;
//height = 1024;
var IMG_URL =  BASEURL+'/getImage?imageName=';
height=640;
width=320;
//var js = require('./开场A1_Canvas.js')
//const URL = "http://10.18.32.120:8086";
var lastNavTime = "";
var lastNavTime2 = "";
var lastNavTime3= "";
var lastNavTime4= "";
export default class TempEdit extends Component{
  static navigationOptions = ({ navigation }) =>{
    return{
      // title:navigation.getParam('tempTitle'),
      // headerRight:(<View></View>),
      // headerLeft:<BackButton navigation = {navigation}/>
      header: null,
    }
  };
  constructor(props){
    super(props);
    this.state = ({
      type:'text',//底部显示  文字 还是 图片
      editLens:false,
      tempId: this.props.navigation.getParam('tempId'),
			userId: this.props.navigation.getParam('userId'),
			tempImg: this.props.navigation.getParam('tempImg'),
      activeLensId:'',
      textIndex: 0,
      leftActive:0,
      bottomActive:-1,
      modal:false,
      visible: false,
      showBtn:false,
      selectMusic:this.props.navigation.getParam('mp3'),
      text:'',
      pkId:'1',
      html:'',
      img: '',
      lens:{},
      leftData:[ //镜头
        // {img:require('../../images/temp/a1.png')},
        // {img:require('../../images/temp/group1.png')},
        // {img:require('../../images/temp/group2.png')},
        // {img:require('../../images/temp/group3.png')},
        // {img:require('../../images/temp/group4.png')},
        // {img:require('../../images/temp/group5.png')},
        // {img:require('../../images/temp/group6.png')}
      ],
      rightData:[
        {img:require('../../images/temp/arrow-u.png'), title:'上移'},
        {img:require('../../images/temp/arrow-d.png'), title:'下移'},
        //{img:require('../../images/temp/icon_text.png'),title: '文字'},
        {img:require('../../images/temp/icon_img.png'),title: '添加图片'},
        {img:require('../../images/temp/icon_music.png'),title: '音乐'},
        {img:require('../../images/temp/icon_camera.png'),title: '更改镜头'},
        {img:require('../../images/temp/icon_add.png'),title: '插入镜头'},
        {img:require('../../images/temp/icon_del.png'),title: '删除'},
        {img:require('../../images/temp/icon_save.png'),title: '保存'},
        //{img:require('../../images/temp/icon_cancel.png'),title: '撤销'},
      ],
      bottomImgData:[
        // {img:require('../../images/temp/group7.png')},
        // {img:require('../../images/temp/group8.png')},
        // {img:require('../../images/temp/group9.png')},
        // {img:require('../../images/temp/group10.png')},
        // {img:require('../../images/temp/group11.png')},

      ],
      bottomTextData:[]
    })
  }
  componentWillMount() {
    Orientation.lockToLandscape();
    //this.getData(1);
    //this._getDetail(1);
    
  }
  componentDidMount(){
    this._getLensList(this.state.tempId, this.state.userId);
  }
  componentWillUnmount() {
    Orientation.lockToPortrait();
  }
  _back(){
    const {navigation} = this.props;
    if(navigation){
      navigation.pop();
    }
  }
  //获取镜头列表
  _getLensList(tempId, userId){
    this.refs.tipModal._loading();
    fetch(BASEURL+'temp/lensList?tempId='+tempId+'&userId='+userId)
    .then(res=>res.json())
    .then(result=>{
      this.refs.tipModal._close();
      //console.log('result',result);
      if(result.succ == '1'){
        // result.list.forEach(item => {
        //   item.img = IMGURL + item.lensImg;
        // })
        result.list.forEach((item, index) => {
          item.sortSeq = index;
        })
        //console.log('list',result.list);
        this.setState({
          leftData: result.list,
          bottomImgData: result.list.length==0 ? [] : this._getLensImgs(result.list[0].oldLensId, result.list[0].lensImgs),
          bottomTextData: result.list.length==0 ? []: this._getLensText(result.list[0].lensText),
          activeLensId: result.list.length==0 ? '' : result.list[0].lensId,
        },()=>{
          if(result.list.length > 0){
            //this.getLensHtml(result.list[0].lensId);
            //this.getLensPng(result.list[0].lensId);
            //console.log('img-',BASEURL+'/getImage?imageName='+ result.list[0].lensId+"/"+result.list[0].lensImg)
            this.setState({
              img: IMG_URL+ result.list[0].oldLensId+"/"+result.list[0].lensImg
            })
          }
        })
      }
      
    })
  }
  //组装底部的可编辑图片数据
  _getLensImgs(oldLensId,lensImgs){
    if(!lensImgs) return [];
    let imgs = lensImgs.split(',');
    let img = [];
    imgs.forEach(item => {
      let obj = {};
      obj.img = IMG_URL + oldLensId+'/'+item;
      img.push(obj);
    })
    //console.log('imgs',img);
    return img;
  }
  _getLensText(lensText){
    if(!lensText) return [];
    let texts = lensText.split(',');
    let text = [];
    texts.forEach(item => {
      let obj = {};
      obj.text = item;
      text.push(obj);
    })
    return text;
  }
  _leftSelect(index){
    this.setState({
      type:'text',
      leftActive:index,
      bottomImgData: this._getLensImgs(this.state.leftData[index].oldLensId, this.state.leftData[index].lensImgs),
      bottomTextData: this._getLensText(this.state.leftData[index].lensText),
      activeLensId: this.state.leftData[index].lensId,
    },()=>{
      //this.getLensHtml(result.list[0].lensId);
      //this.getLensPng(result.list[0].lensId);
      let oldLensId = this.state.leftData[index].oldLensId;
      this.setState({
        img: IMG_URL+ oldLensId+'/'+this.state.leftData[index].lensImg+'&time='+Date.now()
      })
    })
  }
  _bottomClick(index,type){
    const {navigation} = this.props;
    if(type == 'image'){
      //jumpPage(this.props.navigation, 'selectImage');
      if(lastNavTime+1000 >= Date.now()){
        return;
      }
      lastNavTime = Date.now();
      if(navigation){
        navigation.push('selectImage',
          { userId:this.state.userId,
            callback: (data)=>{
              this._handleSelectImage(data,index);
            }
          }
        );
      }
      // ImagePicker.openPicker({
      //   cropping: false
      //   this.uploadFile(index,image.path);
      // });
    } else {//文字
      this.setState({
        modal: true,
        textIndex: index
      })
    }
  }
  _handleSelectImage(imageId,index){
    this.refs.tipModal._loading();
    fetch(BASEURL+'temp/selectImage?lensId='+this.state.activeLensId+'&index='+index+'&imageId='+imageId)
    .then(res=>res.json())
    .then(result=>{
      this.refs.tipModal._close();
      if(result.succ == '1'){
        this._handleImage(result,index);
      }
    })
    
  }
  _handleImage(result,index){
     let leftData = this.state.leftData;
      var activeOldLensId;
      leftData.forEach(item => {
        if(item.lensId == this.state.activeLensId){
          activeOldLensId = item.oldLensId;
          let lensImgs = item.lensImgs;
          let lensList = lensImgs.split(',');
          lensList[index]= result.imageName;
          item.lensImgs = lensList.join(',');
          item.lensImg = result.lensImg;
        }
      })
      let editImgs = this.state.bottomImgData;
      const PATH = IMG_URL + activeOldLensId+'/';
      editImgs[index].img = PATH + result.imageName;
      //console.log('下面-', BASEURL+'/getImage?imageName='+activeOldLensId+'/'+result.imageName);
      this.setState({
        leftData: leftData,
        bottomImgData:editImgs,
        img: PATH + result.lensImg
      },()=>{
        this._renderLeft();
      })
  }
  uploadFile(index, imagePath){
    var url = BASEURL+'temp/uploadFile';
    var formData = new FormData();
    //安卓下   image_uri
    //var image_uri = 'file:///storage/emulated/0/Pictures/image-1bcca3fe-c655-48ca-b1ad-6f6bab28a681.jpg';
    //ios下   img_uri  /Users/ashleydw/Library/Developer/CoreSimulator/Devices/23EE88D0-6E91-43AD-A3B6-06F87698C5A8/data/Containers/Data/Application/A73E68D3-7424-4301-9934-AD0F8251C1EB/tmp/7803DA8A-0E40-4FCB-A593-884805878172.jpg
    var fileName = imagePath.substring(imagePath.lastIndexOf("/")+1,imagePath.length);
    let file = {uri: imagePath, type: 'multipart/form-data', name: fileName};
    formData.append("file",file);
    formData.append("index",index);
    formData.append("userId", this.state.userId);
    formData.append("lensId", this.state.activeLensId);
    fetch(url,{
      method:'POST',
      headers:{
          'Content-Type':'multipart/form-data',
      },
      body:formData,
    })
    .then((response) => response.json() )
    .then((responseData)=>{
      console.log('responseData',responseData);
      this._handleImage(responseData,index);
      // let leftData = this.state.leftData;
      // var activeOldLensId;
      // leftData.forEach(item => {
      //   if(item.lensId == this.state.activeLensId){
      //     activeOldLensId = item.oldLensId;
      //     let lensImgs = item.lensImgs;
      //     let lensList = lensImgs.split(',');
      //     lensList[index]= responseData.imageName;
      //     item.lensImgs = lensList.join(',');
      //     item.lensImg = responseData.lensImg;
      //   }
      // })
      // let editImgs = this.state.bottomImgData;
      // editImgs[index].img = BASEURL+'/getImage?imageName='+activeOldLensId+'/'+responseData.imageName;
      // console.log('下面-', BASEURL+'/getImage?imageName='+activeOldLensId+'/'+responseData.imageName);
      // this.setState({
      //   leftData: leftData,
      //   bottomImgData:editImgs,
      //   img: BASEURL+'/getImage?imageName='+ activeOldLensId+'/'+responseData.lensImg
      // },()=>{
      //   this._renderLeft();
      // })
    })
    .catch((error)=>{
      console.error('error',error);
      this.refs.toast.show("上传失败");
    });
  }

  //预览
  _view(){
		if(this.state.leftData.length<=0){
			this.refs.tipModal._error('请至少添加一个镜头',1500);
			return;
		}
    this.setState({
			showBtn:true,
      visible:true
    })
    // let lensList = [];
    // this.state.leftData.forEach(item => {
    //   let lens = {};
    //   lens.lensId = item.lensId;
    //   lens.during = item.during;
    //   lens.name = item.lensName;
    //   lensList.push(lens);
    // })
    // jumpPage(this.props.navigation, 'tempView',{tempId: this.state.tempId, userId: this.state.userId, lensList,mp3: this.state.selectMusic});
  }
  //预览
  _preview(type){
    this.setState({
			showBtn:false,
      visible:false
    })
    if(type == 1){ //单镜头预览
      let lensList = [];
      let lens = this.state.leftData[this.state.leftActive];
      lensList.push(lens);
      jumpPage(this.props.navigation, 'tempView',{single:true,tempId: this.state.tempId, userId: this.state.userId, lensList,mp3: this.state.selectMusic});
    } else { //全部预览
      let lensList = [];
      this.state.leftData.forEach(item => {
        let lens = {};
        lens.lensId = item.lensId;
        lens.during = item.during;
        lens.name = item.lensName;
        lensList.push(lens);
      })
      jumpPage(this.props.navigation, 'tempView',{single:false, tempId: this.state.tempId, userId: this.state.userId, lensList,mp3: this.state.selectMusic});
    }
  }
  //左侧调整顺序
  _sort(type){
    
    //+1 下移   -1 上移
    let {leftActive, leftData} = this.state;
    //var arr = leftData;
    if(type == 1 && leftActive >= leftData.length-1){
      return;
    } 
    if(type == -1 && leftActive == 0){
      return;
    }
    let x = leftActive, y = leftActive + type;

    let tempObj = leftData[x];
    leftData[x] = leftData[y];
    leftData[y] = tempObj;
    //let array = arr.splice(x - 1, 1, ...arr.splice(y - 1, 1, arr[x - 1]))
    this.setState({
      leftData: leftData,
      leftActive: leftActive + type
    },()=>{
      this._renderLeft();
    })
  }
  _rightClick(index){
    const {navigation} = this.props;
    if(index == 0){
      //this._sort(-1);
    } else if(index == 1){ //文字
      this.setState({
        type:'text'
      })
      //this._sort(1);
    } else if(index == 2){ //图片
      this.setState({
        type:'image'
      })
      // ImagePicker.openPicker({
      //   width: 300,
      //   height: 400,
      //   cropping: false
      // }).then(image => {
      //   console.log(image);
      //   this.setState({
      //     img:image.path,
      //   })
      // });
    } else if(index == 3){ //镜头
      this.setState({
        editLens: true,
      })
    } else if(index == 4){ //音乐 
      //jumpPage(this.props.navigation, 'tempMusic');
      if(lastNavTime4+1000 >= Date.now()){
        return;
      }
      lastNavTime4 = Date.now();
      if(navigation){
        navigation.push('tempMusic',
          {	userId:this.state.userId,
            callback: (mp3)=>{
              this.setState({
                selectMusic:mp3
              })
              //this._handleSelectLens(data,1);
            }
          }
        );
      }
    } else if(index == 5){//插入镜头
      // if(lastNavTime2+1000 >= Date.now()){
      //   return;
      // }
      // lastNavTime2 = Date.now();
      // if(navigation){
      //   navigation.push('selectLens',
      //     {
      //       callback: (data)=>{
      //         this._handleSelectLens(data,0);
      //       }
      //     }
      //   );
      // }
    } else if(index == 6){ //删除
      //this._deleteLen();
    } else if(index == 7){ //保存
      this._saveLens(1);
    } else if(index == 8){ //退出
      this._back();
    } else if(index == 11){
      this._sort(-1);
    } else if(index == 12){
      this._sort(1);
    } else if(index == 13){ //插入
      if(lastNavTime2+1000 >= Date.now()){
        return;
      }
      lastNavTime2 = Date.now();
      if(navigation){
        navigation.push('selectLens',
          {
            callback: (data)=>{
              this._handleSelectLens(data,0);
            }
          }
        );
      }
    } else if(index == 14){ //更换
      if(lastNavTime3+1000 >= Date.now()){
        return;
      }
      lastNavTime3 = Date.now();
      if(navigation){
        navigation.push('selectLens',
          {
            callback: (data)=>{
              this._handleSelectLens(data,1);
            }
          }
        );
      }
    } else if(index == 15){ //删除镜头
      this._deleteLen();
    } else if(index == 16){
      this.setState({
        editLens: false,
      })
    }
  }
  //删除一个镜头
  _deleteLen(){
    if(this.state.leftData.length == 0)
      return;
    let lens = this.state.leftData[this.state.leftActive];
    fetch(BASEURL+'temp/deleteLens?lensId='+lens.lensId+'&userId='+this.state.userId)
    .then(res=>res.json())
    .then(result=>{
      if(result.succ == '1'){
        if(this.state.leftActive == 0){
          this.setState({
            leftData: [],
            bottomImgData: [],
            bottomTextData: [],
            img: '',
          });
          return;
        }
        let leftActive = this.state.leftActive;
        if(this.state.leftActive == this.state.leftData.length -1 ){
          //alert('最后一个');
          leftActive = (this.state.leftActive-1);
        }
        let leftData = this.state.leftData;
        leftData.splice(this.state.leftActive,1);
        //alert(leftActive);
        let lensUser = leftData[leftActive];
        this.setState({
          leftData:leftData,
          bottomImgData: lensUser.lensImgs ? this._getLensImgs(lensUser.oldLensId, lensUser.lensImgs) : [],
          bottomTextData: lensUser.lensText ? this._getLensText(lensUser.lensText) : [],
          img: IMG_URL + lensUser.oldLensId+'/'+lensUser.lensImg
        },()=>{
          this._renderLeft();
        })
      }
    })
    
  }
  //处理选择的镜头
  _handleSelectLens(lens,len){
    //先插入一条镜头数据
    fetch(BASEURL+'temp/insertLens?tempId='+this.state.tempId
      +'&lensId='+lens.lensId+'&userId='+this.state.userId)
    .then(res=>res.json())
    .then(response=>{
      if(response.succ == '1'){
        let leftData = this.state.leftData;
        let lensUser = response.lensUser;
        leftData.splice(this.state.leftActive,len,lensUser);
        this.setState({
          activeLensId:lensUser.lensId,
          leftData:leftData,
          bottomImgData: lensUser.lensImgs ? this._getLensImgs(lensUser.oldLensId, lensUser.lensImgs) : [],
          bottomTextData: lensUser.lensText ? this._getLensText(lensUser.lensText) : [],
          img: IMG_URL + lensUser.oldLensId+'/'+lensUser.lensImg
        },()=>{
          this._renderLeft();
        })
      }
      
    })
    console.log('leftActive',this.state.leftActive)
    console.log('selectLens is -',lens);
  }
  //保存镜头  type:1  点击保存   2,点击合成
  _saveLens(type){
    let lensIds = [];
    this.state.leftData.forEach(item => {
      lensIds.push(item.lensId);
		})
		if(type ==1 ){
			this.refs.tipModal._loading();
		}
    
    fetch(BASEURL+'temp/saveTemp?tempId=' + this.state.tempId+'&lensIds='+lensIds+'&userId='+this.state.userId+'&mp3='+this.state.selectMusic)
    .then(res=>res.json())
    .then(response=>{
      this.refs.tipModal._close();
      console.log('res',response)
      console.log(response.succ == '1');
      if(response.succ == '1'){
				console.log('success')
				if(type ==1 ){
					this.refs.tipModal._success('保存成功',1500)
				} else {
					jumpPage(this.props.navigation, 'compound',{
						tempId:this.state.tempId,
						userId:this.state.userId,
						tempImg:this.state.tempImg
					});
				}
        //this.refs.toast.show("保存成功");
      }
    })
    .catch(err=>{

    })
  }
  _textChange(val){
    this.setState({
      text:val,
    })
  }
  
  _saveText(){
    if(!this.state.text) return;
    this.refs.tipModal._loading();
    fetch(BASEURL+'temp/updateText?lensId=' + this.state.activeLensId+'&text='+this.state.text+'&index='+this.state.textIndex)
    .then(res=>res.json())
    .then(response=>{
      this.refs.tipModal._close();
      console.log('res',response)
      if(response.succ == '1'){
        let leftData = this.state.leftData;
        // leftData.forEach(item => {
        //   if(item.lensId == this.state.activeLensId){
        //     let lensText = item.lensText;
        //     let lensList = lensText.split(',');
        //     lensList[this.state.textIndex]= this.state.text;
        //     item.lensText = lensList.join(',');
        //   }
        // })''
        let tempArr = this.state.leftData;
        tempArr[this.state.leftActive] = response.lens;

        let editTexts = this.state.bottomTextData;
        editTexts[this.state.textIndex].text = this.state.text
        this.setState({
          leftData: tempArr,
          bottomTextData:editTexts,
          img: IMG_URL+ response.lens.oldLensId+'/'+response.lens.lensImg+'&time='+new Date(),
          modal:false,
        })
      }
    })
    
  }
  //合成
  _compose(){
		if(this.state.leftData.length<=0){
			this.refs.tipModal._error('请至少添加一个镜头',1500)
		} else {
			this._saveLens(2);
			//jumpPage(this.props.navigation, 'compound',{tempId:this.state.tempId,userId:this.state.userId});
			
		}
		
		/*
    this.refs.tipModal._loading();
    fetch(BASEURL+'temp/compose?userId='+this.state.userId+'&tempId='+this.state.tempId)
    .then(res => res.json())
    .then(result =>{
      this.refs.tipModal._close();
      if(result.succ == '1'){
        this.refs.tipModal._success('合成申请提交成功，请等待管理员审核',2500)
      } else {
        this.refs.tipModal._error('合成失败',2500)
      }
		})
		*/
  }
  _toggle(){
    this.setState({
			visible: !this.state.visible,
      showBtn: !this.state.showBtn
    })
  }
  _renderLeft(){
    let {leftData} = this.state;
    let view = [];
    let index = 0;
    for(let i=0; i<leftData.length; i++){
      let item = leftData[i];
      index = i+1;
      console.log('image',BASEURL+'/getImage?imageName='+item.oldLensId+'/'+item.lensImg);
      let bigStyle;
      if(this.state.leftActive == i){
        bigStyle = {
          width:height/5-10,
          marginLeft:5
        }
      }
      view.push(
        <TouchableOpacity style={styles.leftImgView} key={item.lensId} onPress={()=>{this._leftSelect(i)}} activeOpacity={0.6}
          style={[styles.leftCell,i==this.state.leftActive?styles.leftCellActive:null]}>
          <Image style={[styles.leftImg,bigStyle]} source={{uri: BASEURL+'/getImage?imageName='+item.oldLensId+'/'+item.lensImg}}/>
        </TouchableOpacity>
      )
    }
    while(index < 6){
      view.push(
        <TouchableOpacity style={[styles.leftImg,{borderWidth:1,borderColor:'#bbb',backgroundColor:'#E1DFDA'}]} key={index+1}  activeOpacity={0.6}
          >
        </TouchableOpacity>
      )
      index++;
    }
    return view;
  }
  _renderBtn(){
    let {rightData} = this.state;
    if(!this.state.editLens){
      return( 
        <View style={[styles.rightBtnBox,{borderWidth:0
        ,borderColor:'red'}]}>
          <View style={styles.row}>
            <BtnComp title='文字' img={require('../../images/temp/i_text.png')} press={()=>this._rightClick(1)}/>
            <BtnComp title='图片' img={require('../../images/temp/i_image.png')} press={()=>this._rightClick(2)}/>
          </View>
          <View style={styles.row}>
            <BtnComp title='镜头' img={require('../../images/temp/i_lens.png')} press={()=>this._rightClick(3)}/>
            <BtnComp title='音乐' img={require('../../images/temp/i_music.png')} press={()=>this._rightClick(4)}/>
          </View>
          {/* <View style={styles.row}>
            <BtnComp title='撤销' img={require('../../images/temp/i_back.png')} press={()=>this._rightClick(5)}/>
            <BtnComp title='重置' img={require('../../images/temp/i_reset.png')} press={()=>this._rightClick(6)}/>
          </View> */}
          <View style={styles.row}>
            <BtnComp title='保存' img={require('../../images/temp/i_save.png')} press={()=>this._rightClick(7)}/>
            <BtnComp title='退出' img={require('../../images/temp/i_exit.png')} press={()=>this._rightClick(8)}/>
          </View>
        </View>
      )
    }
    //镜头
    return(
      <View style={styles.rightBtnBox}>
        <View style={{borderColor:'red',borderWidth:0,width:height*0.16,alignItems:'center',backgroundColor:'#252635'}}>
          <Text style={{padding:0,fontSize:18,color:'#fff',paddingTop:2,paddingBottom:2}}>镜 头</Text>
        </View>
        <View style={styles.row}>
          <BtnComp title='上移' img={require('../../images/temp/i_up.png')} press={()=>this._rightClick(11)}/>
          <BtnComp title='下移' img={require('../../images/temp/i_down.png')} press={()=>this._rightClick(12)}/>
        </View>
        <View style={styles.row}>
          <BtnComp title='插入' img={require('../../images/temp/i_insert.png')} press={()=>this._rightClick(13)}/>
          <BtnComp title='更换' img={require('../../images/temp/i_change.png')} press={()=>this._rightClick(14)}/>
        </View>
        <View style={styles.row}>
          <BtnComp title='删除' img={require('../../images/temp/i_del.png')} press={()=>this._rightClick(15)}/>
          <BtnComp title='退出' img={require('../../images/temp/i_exit.png')} press={()=>this._rightClick(16)}/>
        </View>
      </View>
    )
  }
  _renderBottomView(){
    let {bottomImgData, bottomTextData} = this.state;
    let view = [];
    let count = 0;
    if(this.state.type == 'image'){
      for(let i=0; i<bottomImgData.length; i++){
        let item = bottomImgData[i];
        count = i+1;
        view.push(
          <TouchableOpacity style={[styles.bottomImgView,
            {marginRight:bottomImgData.length-1 === i?0:4}]} 
            key={item.img} activeOpacity={0.6} onPress={()=>this._bottomClick(i,'image')}>
            <Image style={[styles.bottomImg,{borderColor:this.state.bottomActive===i?'blue':'#aaa'}]} source={{uri:item.img}}/>
          </TouchableOpacity>
        )
      }
    }
    if(this.state.type == 'text'){
      for(let i=0; i<bottomTextData.length; i++){
        let item = bottomTextData[i];
        count = i+1;
        view.push(
          <TouchableOpacity style={[styles.bottomImgView,
            {marginRight:4,}]} 
            key={i} activeOpacity={0.6} onPress={()=>this._bottomClick(i,'text')}>
            <View style={{flex:1,margin:0,backgroundColor:'#202133',justifyContent:'center', alignItems:'center'}}>
              <Text style={{color:'white',fontSize:16}}>{item.text}</Text>
            </View>
          </TouchableOpacity>
        )
      }
    }
    while(count < 5){
      view.push(
        <TouchableOpacity style={[styles.bottomImgView,{borderWidth:0,borderColor:'yellow',
        marginRight:count==5?0:4,backgroundColor:'#202133'}]} 
          key={count} activeOpacity={0.6} >
          
        </TouchableOpacity>
      )
      count++;
    }
    return view;
  }
	_reset() {
    //this.refs.scrollView.scrollTo({y: 0});

  }
  _onFocus(refName) {
		return;
			setTimeout(()=> {

					let scrollResponder = this.refs.scrollView.getScrollResponder();
					scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
							findNodeHandle(this.refs[refName]), 0, true);

			}, 100);
	}
  render(){
    //<Image style={styles.middleImg} source={require('../../images/temp/group11.png')}/>
    console.log('pkId',this.state.pkId);
    return(
			<View style={{flex:1,backgroundColor:'#f0f0f0'}}>
				<StatusBar hidden={true}/>
        <View style={[styles.container,{padding:10}]}>
          <View style={[styles.leftView,{backgroundColor:'#fff'}]}>
            <ScrollView style={{flex:1}} showsVerticalScrollIndicator={false}>
              {this._renderLeft()}
            </ScrollView>
          </View>
          <View style={{flex:1}}>
            <View style={[styles.middleView]}>
              <View style={{flex:1,marginTop:0,marginLeft:5,backgroundColor:'white',
                //borderWidth:StyleSheet.hairlineWidth,
                padding:5}}>
                <Image style={{width:'100%',height:'100%',resizeMode:'stretch'}} source={{uri:this.state.img}}/>
              </View>
              <View style={[styles.rightView,{borderWidth:0}]}>
                {this._renderBtn()}
                <View style={{borderColor:'red',width:'100%',borderWidth:0,marginTop:2,backgroundColor:'#f0f0f0'}}>
                  <MyButton text='预览' btnStyle={{marginLeft:10,marginRight:10,marginTop:0,height:24}} press={()=>this._view()}/>
                  <MyButton text='合成' btnStyle={{marginLeft:10,marginRight:10,marginBottom:10,marginTop:5,height:24,marginBottom:5}} press={()=>this._compose()}/>
                </View>
              </View>
            </View>
            <View style={styles.bottomView}>
              <ScrollView horizontal={true} showsHorizontalScrollIndicator={false} style={{height:'100%',}}>
                {this._renderBottomView()}
              </ScrollView>
            </View>
          </View>
        
        
        <Toast ref="toast" position='bottom' positionValue={200} />
        <TipModal ref="tipModal"/>
        <Modal animationType='none' 
          transparent={true} 
          visible={this.state.modal} 
          onRequestClose={() => {this.setState({modal:false})}}
          style={styles.modal}
          >
          
					<View style={styles.mView}>
					{/* <ScrollView style={{flex:1}} ref="scrollView"> */}
					<KeyboardAvoidingView>
            <View style={[styles.lView]}>
							
              <View style={{
                borderColor:'#888',
                borderTopWidth:StyleSheet.hairlineWidth,
                borderBottomWidth:StyleSheet.hairlineWidth,
              }}>
							
                <TextInput 
                  ref="textInput"
                  placeholder='请输入文字'
                  style={styles.searchInput}
                  underlineColorAndroid="transparent"
                  onChangeText={(val)=>this._textChange(val)}
                  returnKeyType='done'
                  placeholderTextColor='#aaa'
									onBlur={this._reset.bind(this)}
                  onFocus={this._onFocus.bind(this, 'textInput')}
                />
              </View>
              
              <MyButton text='确定' press={()=>this._saveText()} 
              btnStyle={{marginLeft:1,marginRight:1,marginTop:0,
                paddingLeft:10,paddingRight:10,
              marginBottom:1,borderRadius:5,}}/>
            </View>
						</KeyboardAvoidingView>
						{/* </ScrollView> */}
					</View>
          
        </Modal>
        <Modal animationType='none' 
          transparent={true} 
          visible={this.state.visible} 
          onRequestClose={() => {this.setState({visible:false})}}
          style={{flex:1}}
          >
          <TouchableOpacity style={styles.mmView} activeOpacity={1.0} onPress={() => this._toggle()}>
          { !this.state.showBtn ? null :
            <View style={[styles.llView]}>
              <MyButton text='单镜头预览' press={()=>this._preview(1)} 
                btnStyle={{marginLeft:0,marginRight:1,marginTop:0,width:110,
                paddingLeft:10,paddingRight:10,backgroundColor:'rgba(0,0,0,0.5)',
              marginBottom:1,borderRadius:5,}}/>
              <MyButton text='全部预览' press={()=>this._preview(2)} 
                btnStyle={{marginLeft:1,marginRight:1,marginTop:10,width:110,
                paddingLeft:10,paddingRight:10,backgroundColor:'rgba(0,0,0,0.5)',
              marginBottom:1,borderRadius:5,}}/>
            </View>
          }
          </TouchableOpacity>
        </Modal>
      </View>
			</View>
    );
  }
}
class BtnComp extends Component{
  render(){
    const rightImg = {
      width:18,
      height:18,
      resizeMode:'contain',
      //borderColor:'red',
      // /borderWidth:StyleSheet.hairlineWidth,
    }
    const rightText = {
      marginTop:3,
      color:'#7b7b7b',
      fontSize:12,
    }
    return(
      <TouchableOpacity style={[styles.rightIconView,]}  activeOpacity={0.6} onPress={this.props.press}>
        {this.props.img ?
          <Image style={rightImg} source={this.props.img}/>
          :null
        }
        <Text style={rightText}>{this.props.title}</Text>
      </TouchableOpacity>
    )
  }
}
const styles = StyleSheet.create({
  llView:{
		backgroundColor:'rgba(0,0,0,0.0)',
		opacity:1,
    justifyContent:'center',
    alignItems:'center',
		marginRight:10,
		bottom:10,
  },
  mmView:{
    flex:1,
    borderWidth:0,
    flexDirection:'row',
    justifyContent:'flex-end',
    alignItems:'flex-end',
    marginBottom:50,
    marginRight:50,
    backgroundColor:'rgba(0, 0, 0, 0.0)',
  },
  bottomBtnView:{
  //backgroundColor:'#f00000',
    marginLeft:8,
    marginRight:10,
    justifyContent:'center',
    alignItems:'center'
  },  
  btnImg:{
    width:'100%',
    height:34,
    resizeMode:'contain',
    //borderColor:'orange',
    //borderWidth:1,
  },
  
  searchInput:{
    marginLeft:15,
    padding:0,
    flex:1,
    height: 46, 
    fontSize:15,
    width:height/3,
  },
  lView:{
    backgroundColor:'white',
    opacity:1,
    borderRadius:5,
    padding:10,
    justifyContent:'center',
    alignItems:'center',
    flexDirection:'row',
    width:height/2,
  },
  mView:{
    flex:1,
    borderWidth:1,
    //opacity:0.5,
    justifyContent:'center',
    // marginTop:20,
    alignItems:'center',
    backgroundColor:'rgba(0, 0, 0, 0.5)',
  },
  modal:{
    flex:1,
    marginTop:40,
  },
  bottomView:{
    alignItems:'center',
    height:height/7,
    marginLeft:5,
    marginBottom:0,
    marginTop:6,
    padding:5,
    backgroundColor:'white',
    // borderWidth:StyleSheet.hairlineWidth,
    // borderColor:'red',
  },
  bottomImgView:{
    // marginTop:4,
    // marginBottom:4,
    width:(height/7-10)*1.3,
    height:height/7-10,
    borderWidth:StyleSheet.hairlineWidth,
    borderColor:'#666',
  },
  bottomImg:{
    width:'100%',
    height:'100%',
    borderRadius:4,
    borderWidth:1,
    resizeMode:'contain',
  },
  leftImgView:{
    width:height/5,
    height:height/5/16*9,
    // borderWidth:StyleSheet.hairlineWidth,
    // borderColor:'red',
    shadowColor: 'rgba(0, 0, 0, 0.5)',
    shadowOffset: {
        width: 2,
        height: 3
    },
    shadowRadius: 2,
    elevation: 2,
  },
  leftImg:{
    width:height/5-20,
    height:(height/5-20)*0.625,
    borderWidth:1,
    margin:5,
    marginLeft:10,
    borderRadius:2,
  },
  leftView:{
    width:height/5,
    backgroundColor:'white'
    // borderWidth:1,
    // borderColor:'green'
  },
  
  middleView:{
    flex:1,
    flexDirection:'row',
    // borderWidth:1,
    // borderColor:'blue'
  },
  middleImg:{
    width:'100%',
    height:'100%',
  },
  row:{
    flexDirection:'row',
    // borderColor:'#00bfff',
    // borderWidth:StyleSheet.hairlineWidth,
    paddingTop:10,
    paddingBottom:0,
    flex:1,
  },
  rightBtnBox:{
    flex:1,
    flexDirection:'column',
    height:'100%',
    flexWrap:'wrap',
    borderColor:'#aaa',
    borderWidth:StyleSheet.hairlineWidth,
    alignItems:'center',
    justifyContent:'flex-start',
    backgroundColor:'white',
    // marginTop:0,
    // marginLeft:8,
    // marginRight:10,
    // marginBottom:10,
  },
  
  rightView:{
    marginLeft:10,
    width:height*0.16,
    height:'100%',
    justifyContent:'space-between',
    alignItems:'center'
    // borderWidth:1,
    // borderColor:'green'
  },
  rightIconView:{
    //borderBottomColor:'#aaa',
    //borderBottomWidth:StyleSheet.hairlineWidth,
    //borderColor:'green',
    //borderWidth:StyleSheet.hairlineWidth,
    width:'50%',

    justifyContent:'center',
    alignItems:'center',
  },
  container: {
    backgroundColor:'#f0f0f0',
    flex: 1,
    flexDirection:'row',
  },
})